public without sharing class QuoteEquipmentController {

	public String msg {get; private set;}
	public Boolean isErr {get; private set;}
	public Boolean isSuccess {get; private set;}
	public String backId {get;private set;}
	public String qid ; 

	public String paramJson {get;private set;}
	public String saveJson {get; set;}
    public String searchJson {get; private set;}

	public Quote q {get ;private set;}
	public  Boolean isNew {get; private set;}
	private User u ;
  private String  sealflag;

	//public String policycombox {get;private set;}
	//public String coopcombox {get; private set;}
    public String recordtypeName {get; private set;}

    public String cate1combox {get; private set;}
    public String cate2combox {get; private set;}
    public String cate3combox {get; private set;}
    //public String dataJson {get; private set;}
    public Boolean isLookInvoiceDealerPrice{get; private set;}

    public Boolean isNeedSelectAccount {get ;private set;} //是否需要选择 报价适用 的终端客户
    //public String applicableAccountParam {get;set;}//适用的客户
    public Opportunity opp {get;private set;}

    private String province;

    private String company;
	public class ControllerException extends Exception {}


    public QuoteEquipmentController() {
        qid = System.currentPageReference().getParameters().get('id');
        q = new Quote();
        isNew = false;
        backId = qid; 
        u  = [select Id, SubCompany__c,Profile.Name  from User where Id =:UserInfo.getUserId()];
        isLookInvoiceDealerPrice  = u.Profile.Name != '销售部直销销售员';
    }

    public String getOptMap(Map<String,String> opts){
       Map<String ,Object> cooMap = new Map<String ,Object> ();
      cooMap.put('valueField', 'value');
      cooMap.put('textField', 'label');
      cooMap.put('panelHeight', 'auto');
      cooMap.put('limitToList', 'true');
      List<Map<String,String>>  dList = new List<Map<String,String>>();
      for (String k : opts.keySet()) {
        Map<String ,String> dataMap = new Map<String,String>();
        dataMap.put('label',opts.get(k) );
        dataMap.put('value',k );
        dList.add(dataMap);
      }  
      cooMap.put('data', dList);   
      
      return EncodingUtil.urlEncode(JSON.serialize(cooMap), 'UTF-8');
    }

    public void init(){

    	try{


            Map<String,String> cm = ImportObject.getPicklistValues('Contract__c','Corpcode__c',false);
            if(cm.get(u.SubCompany__c) == null)setErr('公司编码维护错误!请联系管理员维护!');
           
    		 if(qid ==  null)setErr('页面打开错误');
    		//policycombox = getOptMap(ImportObject.getPicklistValues('QuoteProduct__c', 'WhetherImplementPolicyPrice__c',true));
    		//coopcombox = getOptMap(ImportObject.getPicklistValues('QuoteProduct__c','CoopType__c',true));
    		if(Id.valueOf(qid).getSObjectType() == Quote.SObjecttype ){
    		
    			q = [select Id,ApplicableCustomers__c ,ApplicableCustomers__r.Name ,Comment__c,RecordType.DeveloperName,Status ,OpportunityId   from Quote where Id=:qid];
    			if(q.Status == '申请中' || q.Status == '已批准')setErr('报价'+q.Status +'不能修改!');

                recordtypeName = q.RecordType.DeveloperName;
                 //是否需要选择适用客户
                isNeedSelectAccount = (q.RecordType.DeveloperName == 'DealerQuote') ? true  : false  ;
                opp = [select Id,StageName,Owner.PriceProvince__c,Owner.SubCompany__c , AccountId, Account.Name,RecordType.DeveloperName from Opportunity where Id = :q.OpportunityId ];


    		}else if(Id.valueOf(qid).getSObjectType() == Opportunity.SObjectType){
            isNew = true;
                opp = [select Id,StageName,Owner.SubCompany__c, Owner.PriceProvince__c ,AccountId, Account.Name,RecordType.DeveloperName from Opportunity where Id = :qid];

                if(opp.StageName != '立项' && opp.StageName != '招标' && opp.StageName != '方案谈判' && opp.StageName != '意向'  )setErr('不能在业务机会的'+opp.StageName+'阶段仪器报价');
                
				        q.RecordTypeId = (opp.RecordType.DeveloperName == 'DealerOpportunity')? Utils.getRecordTypeIdByDevNameAndObjName('DealerQuote','Quote'): Utils.getRecordTypeIdByDevNameAndObjName('TerminalCustomerInstrumentQuote','Quote');
                //是否需要选择适用客户
                isNeedSelectAccount = (opp.RecordType.DeveloperName == 'DealerOpportunity') ? true  : false  ;

                q.Status= '草案中';
    			      q.OpportunityId= qid; 
                q.Name = opp.Account.Name + '报价-' + Utils.date2string(System.now(), 'YYYYMMDDHHMMSS'); 
                q.Type__c = '仪器报价';
                q.ApplicableCustomers__c= opp.AccountId;
                recordtypeName = (opp.RecordType.DeveloperName == 'DealerOpportunity') ?  'DealerQuote' : 'TerminalCustomerInstrumentQuote';
    		}else{
    			setErr('页面打开错误');
    		}
            if(opp.StageName == '合同签订' || opp.StageName == '市场管理' || opp.StageName == '提起合作确认' || opp.StageName == '失败' )setErr('业务机会在'+ opp.StageName +'阶段,不能新建/修改报价 ');

            province = opp.Owner.PriceProvince__c;
            company = opp.Owner.SubCompany__c; 
            sealflag = 'Y-'+cm.get(u.SubCompany__c);
            cate1combox = getOptsFromLabel(Label.Product_Category1);
            cate2combox = getOptsFromLabel(Label.Product_Category2);
            cate3combox = getOptsFromLabel(Label.Product_Category3);
           // Map<String ,Object>dataMap = new Map<String ,Object>();
          //  dataMap.put('Account',getAccountfield()); 
           // dataMap.put('ApplicableCustomers__c', getApplicationAccountfield());
           // dataJson  = EncodingUtil.urlEncode(JSON.serialize(dataMap), 'UTF-8');

    	    
    	}catch(Exception e) {
    	     ApexPages.addMessage( new ApexPages.Message(ApexPages.Severity.ERROR ,e.getMessage()));
    	     isErr = true;

    	}
    	
    }

     /*private Map<String,List<DataUtil.FieldBean>> getAccountfield(){
        Map<String,List<DataUtil.FieldBean>> searchMap = new Map<String,List<DataUtil.FieldBean>>();

        Map<String,DataUtil.FieldBean>proMap = DataUtil.getFieldsInfo(Account.SObjecttype, new Set<String>{'Name','Province__r.Name'} );
        searchMap.put('Account', proMap.values());
        return searchMap;
    }*/
     /*private Map<String,List<DataUtil.FieldBean>> getApplicationAccountfield(){
        Map<String,List<DataUtil.FieldBean>> searchMap = new Map<String,List<DataUtil.FieldBean>>();

        Map<String,DataUtil.FieldBean>proMap = DataUtil.getFieldsInfo(Quote.SObjecttype, new Set<String>{'ApplicableCustomers__c'} );
        searchMap.put('ApplicableCustomers__c', proMap.values());
        return searchMap;
    }
    ///前端选择后设置终端客户
    public void setApplicableAccount(){
        msg = '';
        try{
           q.ApplicableCustomers__c = Id.valueOf(applicableAccountParam);  
           msg = 'ok';
       }catch(Exception e){
            msg = '设置失败:'+e.getMessage();
       }
        

    }*/
    private String transStr (Set<Id> nset){
      if(nset == null || nset.size()== 0)return '()';
      String s = JSON.serialize(nset);
        s = s.replaceAll('"','\'');
      s = s.replace('[','(');
      s = s.replace(']',')');
      return s;

    }
    private String getOptsFromLabel(String lb){
        Map<String,String> tmpMap = new Map<String,String>();

        tmpMap.put('', System.Label.Option_None);
        for (String str : lb.split(',', -1)) {
            tmpMap.put(str, str);
        }
        return getOptMap(tmpMap);
    }

    private void setErr(String message ){	 
    	isErr  =true;
    	throw new ControllerException(message);

    }
    public void setNil(){
    	paramJson = '[]';
    	saveJson = '[]';
        searchJson = '{}';
       // dataJson = '{}';
    }
    //配置清单
    @RemoteAction
    public static List<MatchBean> lookmatch(String productId ){

        List<MatchBean> lm = new List<MatchBean>();

        if(productId == null || productId.length() == 0) return lm;
        for (ConfigurationListDetail__c cg  :[select Id ,Amount__c,IsStandard__c ,OrderMethod__c,
            Name, Configuration__r.ProductName__c, Configuration__r.Brand__c ,Configuration__r.Spec__c,
            Configuration__r.SerialNo__c,Configuration__r.Unit__c
           from ConfigurationListDetail__c where  InstrumentModel__c =:productId] ) {
           lm.add(new MatchBean(cg)) ;
        }

        return lm;

    }
    public void getDetails(){

    	Map<String,Object> res = new Map<String,Object>();
    	List<QuoteProductBean> tmp = new List<QuoteProductBean>();
    	if(qid != null && Id.valueOf(qid).getSObjectType() == Quote.getSObjectType()){
    		Set<Id> pids = new Set<Id>();
        //CoopType__c,WhetherImplementPolicyPrice__c,CompanyPolicyName__c
    		String sql = 'select Id, Product__c ,Quantity__c, Product__r.ProductName__c,Product__r.Category0__c,Product__r.NCCode__c,'+
    			'Product__r.Category1__c,Product__r.Category2__c,Product__r.Brand__c,Product__r.Spec__c,Product__r.MatchingInstrument__c,'+
    			'Product__r.SerialNo__c,Product__r.Model__c,Account__c,Account__r.Name ,'+
    			'SalesPrice__c,UnitPrice__c,Remarks__c,RelatedProduct__c  '+
    			'from QuoteProduct__c where Quote__c =\''+qid +'\'';

            List<QuoteProduct__c>qpList = Database.query(sql);
           
    		for(QuoteProduct__c qp : qpList){
    			pids.add(qp.Product__c);
    		}
        Map<Id,Price__c> priceMap = ImportObject.getPriceMap(pids, company,province);
       
        for(QuoteProduct__c qp :qpList){
            tmp.add(new QuoteProductBean(qp,priceMap.get(qp.Product__c )));
            pids.add(qp.Product__c);
        }
        //明细数据之间建立 配置关系
        // for(ConfigurationListDetail__c cgl : [select Id,Configuration__c,InstrumentModel__c  from ConfigurationListDetail__c where   SoftWareKit__c = true and Configuration__c in:pids   ]){

        //   for (QuoteProductBean qt  : tmp) {
        //     if(qt.productId == cgl.Configuration__c ){
        //       qt.relatedId = cgl.InstrumentModel__c;
        //       break;
        //     }
        //   }
        // }



    	}
    	res.put('data', tmp);

            List<QuoteProductBean> tmp1 = new List<QuoteProductBean>();
            Set<Id> pids = new Set<Id>();
            String itentsql = 'select Id,Product__c ,Product__r.ProductName__c,Product__r.Category0__c,Product__r.MatchingInstrument__c,'+
              'Product__r.Category1__c,Product__r.Category2__c,Product__r.Brand__c,Product__r.Spec__c,Product__r.NCCode__c,TerminalClient__c, TerminalClient__r.Name ,'+
              'Product__r.SerialNo__c,Product__r.Model__c,Quantity__c from IntentProduct__c  where Opportunity__c =\''+q.OpportunityId+'\'  and Product__r.Category0__c in  ' +Label.EuipmentCategory0 ;
            List<IntentProduct__c> ipList= Database.query(itentsql);
            for(IntentProduct__c ip : ipList ){

              pids.add(ip.Product__c  );


            }


            //加载配套软件保
        String sql1 = ' select Id, Configuration__r.Name  ,Configuration__r.ProductName__c,Configuration__r.Category0__c,InstrumentModel__c,'+
          ' Configuration__r.Category1__c,Configuration__r.Category2__c,Configuration__r.Brand__c,Configuration__r.Spec__c,Configuration__r.NCCode__c,'+
          ' Configuration__r.SerialNo__c,Configuration__r.Model__c,Amount__c from ConfigurationListDetail__c  '+
          ' where SoftWareKit__c = true and  InstrumentModel__c in (select Product__c from IntentProduct__c where   Opportunity__c = \''+q.OpportunityId+'\'  and Product__r.Category0__c in ' +Label.EuipmentCategory0 +'  )  ';
        List<ConfigurationListDetail__c> relatedList = Database.query(sql1);
        //Map<Id,ConfigurationListDetail__c> relatedMap = new Map<Id,ConfigurationListDetail__c >();
        Set<Id> confset = new Set<Id>();
        for(ConfigurationListDetail__c  p:relatedList){
           
           pids.add(p.Configuration__c );
           confset.add(p.Configuration__c);
          // relatedMap.put(p.Configuration__c, p);

        }
        


         

      /*
    	Set<Id> pids = new Set<Id>();
    	String sql = ' select Id  ,ProductName__c,Category0__c,MatchingInstrument__c,'+
    			' Category1__c,Category2__c,Brand__c,Spec__c,NCCode__c,'+
    			' SerialNo__c,Model__c from Product__c '+
    			' where Id in (select Product__c from IntentProduct__c where  Opportunity__c = \''+q.OpportunityId+'\'  and Product__r.Category0__c in ' +Label.EuipmentCategory0 +'  )  ';
        List<Product__c> ipList = Database.query(sql);
    	for(Product__c  p:ipList){
    		pids.add(p.Id );
    	}

      }*/
    	Map<Id,Price__c> priceMap = ImportObject.getPriceMap(pids,company,province);
      Map<Id ,Map<String,Decimal>> terminalMap = new Map<Id,Map<String,Decimal>>();
      Map<String,String > terminalNameMap = new  Map<String,String>();
        for(IntentProduct__c  p:ipList){
            //排除已经存在的配件
            if(confset.contains(p.Product__c))continue;
            String key = p.Product__c +'-'+ (p.TerminalClient__c == null ? '': p.TerminalClient__c);

            terminalNameMap.put(key,p.TerminalClient__r.Name);
            Map<String,Decimal> productNumMap = terminalMap.containsKey(p.Product__c ) ? terminalMap.get(p.Product__c ):new Map<String,Decimal>();

            Decimal num = productNumMap.containsKey(key ) ? productNumMap.get(key)+ (p.Quantity__c== null ? 0 : p.Quantity__c)  : (p.Quantity__c== null ? 0 : p.Quantity__c) ;
            productNumMap.put(key , num);
            tmp1.add(new QuoteProductBean(p,priceMap.get(p.Product__c )));
            //exset.add(p.Product__c);
            terminalMap.put(p.Product__c ,productNumMap);

        }
        System.debug('QuoteEquipmentController==>'+tmp1.size());
        ipList.clear();
        System.debug('QuoteEquipmentController==>'+relatedList);

        for(ConfigurationListDetail__c  p:relatedList){
          
          if(terminalMap.containsKey(p.InstrumentModel__c)){

              for(String key : terminalMap.get(p.InstrumentModel__c).keySet()){
                List<String> keys = key.split('-');
                String terminalId = keys.size() > 1 ? keys.get(1) : null ;
                if(String.isBlank(terminalId))terminalId = null;

                tmp1.add(new QuoteProductBean(p,priceMap.get(p.Configuration__c ),terminalMap.get(p.InstrumentModel__c).get(key),terminalId,terminalNameMap.get(key)));

              }

          }






        }

        System.debug('QuoteEquipmentController==>'+tmp1.size());
      relatedList.clear();
    	res.put('intent', tmp1);
    	paramJson = EncodingUtil.urlEncode(JSON.serialize(res), 'UTF-8');



    }





   /*  public void search(){
          Map<String,Object> searchMap =(Map<String,Object> )JSON.deserializeUntyped(EncodingUtil.urlDecode(saveJson, 'UTF-8'));
          String sql = 'select Id,ProductName__c,MatchingInstrument__c ,Name ,Unit__c, Brand__c,Spec__c,Model__c,SerialNo__c ,SealCompany__c ,NCCode__c,Category1__c,'+
          'Category2__c,Category0__c  from Product__c where Category0__c  in  '+ Label.EuipmentCategory0 +' ';
          

          String relatedSql = sql ; 

          if(String.isBlank(String.valueOf(searchMap.get('name'))) == false)sql += ' and ProductName__c like \'%'+String.valueOf(searchMap.get('name'))+'%\'';
          
          if(String.isBlank(String.valueOf(searchMap.get('brand'))) == false)sql += ' and Brand__c like \'%'+String.valueOf(searchMap.get('brand'))+'%\'';
          
          if(String.isBlank(String.valueOf(searchMap.get('serialno'))) == false)sql += ' and SerialNo__c like \'%'+String.valueOf(searchMap.get('serialno'))+'%\'';
          
          if(String.isBlank(String.valueOf(searchMap.get('model'))) == false)sql += ' and Model__c like \'%'+String.valueOf(searchMap.get('model'))+'%\'';
          
          if(String.isBlank(String.valueOf(searchMap.get('nccode'))) == false)sql += ' and NCCode__c like \'%'+String.valueOf(searchMap.get('nccode'))+'%\'';
          
          if(String.isBlank(String.valueOf(searchMap.get('cate1'))) == false)sql += ' and Category1__c like \'%'+String.valueOf(searchMap.get('cate1'))+'%\'';
          
          if(String.isBlank(String.valueOf(searchMap.get('cate2'))) == false)sql += ' and Category2__c like \'%'+String.valueOf(searchMap.get('cate2'))+'%\'';
          
          if(String.isBlank(String.valueOf(searchMap.get('cate3'))) == false)sql += ' and Category3__c like \'%'+String.valueOf(searchMap.get('cate3'))+'%\'';
                    
         

          sql += '  Limit 200 ';

          Map<String,Object> resMap = new  Map<String,Object>();
          List<QuoteProductBean> tmp = new List<QuoteProductBean>();
          Set<Id> equips = new Set<Id>();
          List<Product__c> pList = (List<Product__c>)SQLUtil.query(sql);
          for(Product__c p : pList){  
            if(!(p.SealCompany__c != null && p.SealCompany__c.contains(sealflag))){
                equips.add(p.Id);
            }
          }
        Map<Id,Price__c> priceMap = ImportObject.getPriceMap(equips, u.SubCompany__c);
          for(Product__c p : pList){          
            if(!(p.SealCompany__c != null && p.SealCompany__c.contains(sealflag))){
                tmp.add(new QuoteProductBean(p,priceMap.get(p.Id )));
            }
          }
          resMap.put('data', tmp);
          System.debug('QuoteEquipmentController==>'+resMap);
          
        if(equips.size() == 0) return;

         relatedSql += ' and MatchingInstrument__c in ' + transStr(equips);

        Map<String,List<QuoteProductBean>> relatedMap = new Map<String,List<QuoteProductBean>>();
              System.debug('QuoteEquipmentController==>'+relatedSql);
         List<Product__c> rpList = Database.query(relatedSql);
         Set<Id> repset = new Set<Id>();
        for(Product__c p : rpList ){
              if(!(p.SealCompany__c != null && p.SealCompany__c.contains(sealflag))){
                  repset.add(p.Id);
              }
        }
        Map<Id,Price__c> repriceMap = ImportObject.getPriceMap(repset, u.SubCompany__c);
        for(Product__c p : rpList ){
          if(!(p.SealCompany__c != null && p.SealCompany__c.contains(sealflag))){
              List<QuoteProductBean> pl =relatedMap.containsKey(p.MatchingInstrument__c) ?relatedMap.get(p.MatchingInstrument__c ) :  new List<QuoteProductBean>();
              pl.add(new QuoteProductBean(p,repriceMap.get(p.Id )));
              relatedMap.put(p.MatchingInstrument__c,pl);

          }
        }
        resMap.put('related',relatedMap);
          System.debug('QuoteEquipmentController==>'+resMap);
          searchJson = EncodingUtil.urlEncode(JSON.serialize(resMap),'UTF-8');

    }
    */

  


    public void save(){

    	msg = '';
    	List<Object> resList = (List<Object>) JSON.deserializeUntyped(EncodingUtil.urlDecode(saveJson, 'UTF-8'));

    	List<QuoteProduct__c> qpList = new List<QuoteProduct__c>();
    	if(resList.size() == 0 ){
    		msg = '没有报价产品!';
    		return ;
    	}
      Map<Id,String> prodMap = new Map<Id,String>();
      Map<String,QuoteProduct__c>   qpMap = new Map<String,QuoteProduct__c>();

      Map<String,String> relatedMap = new Map<String,String>();
    	try {

    		Set<Id> pids = new Set<Id>();
    		for (Object o : resList) {
    			Map<String,Object> mo = (Map<String,Object>) o;
    			QuoteProduct__c qp = new QuoteProduct__c();
    			if(mo.get('productId') == null){
    				msg = '保存失败! 产品信息异常!';
    				return;
    			}
           qp.Product__c = Id.valueOf(getStringVaule(mo.get('productId')));
    			pids.add(qp.Product__c);
          prodMap.put(qp.Product__c,getStringVaule(mo.get('name')) );
    			qp.Quantity__c = getDecimalValue(mo.get('num'));
    			qp.SalesPrice__c = getDecimalValue(mo.get('price'));
    			qp.UnitPrice__c = getDecimalValue(mo.get('unitprice'));

    			qp.Brand__c = getStringVaule(mo.get('brand'));
    			qp.Model__c = getStringVaule(mo.get('model'));
				  qp.Spec__c = getStringVaule(mo.get('spec'));
				  qp.SerialNo__c = getStringVaule(mo.get('serialno'));
				  qp.Category0__c =  getStringVaule(mo.get('cate0'));
				  qp.Category1__c =  getStringVaule(mo.get('cate1'));
				  qp.Category2__c =  getStringVaule(mo.get('cate2'));
				//qp.CoopType__c  = getStringVaule(mo.get('coop'));
				  qp.DiscountRate__c = getDecimalValue(mo.get('discount'));
				  qp.Remarks__c = getStringVaule(mo.get('note'));
          qp.Account__c = getStringVaule(mo.get('terminalId'));

				//qp.WhetherImplementPolicyPrice__c = getStringVaule(mo.get('isPolicy'));
			//	qp.CompanyPolicyName__c = getStringVaule(mo.get('policy'));
          //终端+null+
          //终端+关联Id + 产品Id 
          String relatedId = getStringVaule(mo.get('relatedId')); 

          if(!String.isBlank(relatedId))qp.RelatedProduct__c = relatedId;
    			qpList.add(qp);


    		}


    		Map<Id,Price__c> priceMap = ImportObject.getPriceMap(pids, company,province);
    		Map<Id,AveragePrice__c> aPriceMap = ImportObject.getLastMothPrice(pids, u.SubCompany__c);

        Set<String> errset = new Set<String>();
    		for(QuoteProduct__c qp:qpList){

    			 if (priceMap.containsKey(qp.Product__c) == false) {

                 if(!errset.contains(qp.Product__c))   msg  += prodMap.get(qp.Product__c ) + '(' + Schema.Product__c.fields.SerialNo__c.getDescribe().getLabel() + ':' + qp.serialNo__c + '; ) '
                             + System.Label.Err_NoPrice;
                    errset.add(qp.Product__c );

                    continue;         
                } 
                qp.InstCost__c = priceMap.containsKey(qp.Product__c) ? priceMap.get(qp.Product__c).InstCost__c : null  ; 
                if(qp.InstCost__c == null ) msg += prodMap.get(qp.Product__c ) + '(' + Schema.Product__c.fields.SerialNo__c.getDescribe().getLabel() + ':' + qp.serialNo__c + '; ) '
                             + ' 没有成本价! ';
    			      qp.AreaDealerPrice__c = priceMap.containsKey(qp.Product__c) ? priceMap.get(qp.Product__c).AreaDealerPrice__c : 0;
                qp.InvoiceDealerPrice__c = priceMap.containsKey(qp.Product__c) ? priceMap.get(qp.Product__c).InvoiceDealerPrice__c : 0;
                qp.HospitalManagerPrice__c = priceMap.containsKey(qp.Product__c) ? priceMap.get(qp.Product__c).HospitalManagerPrice__c : 0;
                qp.HospitalBottomPrice__c = priceMap.containsKey(qp.Product__c) ? priceMap.get(qp.Product__c).HospitalBottomPrice__c : 0;
                qp.CompanyBottomPrice__c = priceMap.containsKey(qp.Product__c) ? priceMap.get(qp.Product__c).CompanyBottomPrice__c : 0;
                qp.LastMonthAveragePrice__c = aPriceMap.containsKey(qp.Product__c) ? aPriceMap.get(qp.Product__c).AveragePrice__c : 0;
                qp.SpecialPrice__c = priceMap.containsKey(qp.Product__c) ? priceMap.get(qp.Product__c).SpecialPrice__c : 0 ; 
    			
    		}

    		if(msg.length() > 0) return;


    	    
    	}catch (Exception e) {
    	  	msg = '保存失败!'+e.getMessage();  
    	    return ; 
    	}
    	SavePoint sp = Database.setSavepoint();

    	try {
            System.debug('QuoteEquipmentController==>'+ q);
    	    upsert q; 
            System.debug('QuoteEquipmentController1==>'+ q);

    	    for (QuoteProduct__c qp : qpList) {
    	    	qp.Quote__c = q.Id ;
    	    }
    	    backId = q.Id ; 
    	    delete [select Id from QuoteProduct__c where Quote__c =:q.Id ];
            System.debug('QuoteEquipmentController3==>'+ msg);
    	    if(qpList.size() > 0 ) insert qpList;
            System.debug('QuoteEquipmentController4==>'+ msg);

    	    isSuccess = true;
    	    msg = '保存成功!';

    	}catch (Exception e) {
    	   	Database.rollback(sp);
    	  	msg = '保存失败!'+e.getMessage()+e.getStackTraceString(); 
    	  	if(isNew){
    	  		q.Id = null;
    	  		backId = qid ; 
    	  	} 
    	}
            System.debug('QuoteEquipmentController2==>'+ msg);


    	
    	
    }
    private String getStringVaule(Object o ){
    	if(o == null ) return null;
    	String s = String.valueOf(o).trim();
    	if(s =='')return null;
    	return s; 
    }
    private Decimal getDecimalValue(Object o){
    	String s = getStringVaule(o);
    	if(s == null) return null;
    	return Decimal.valueOf(s);
    }

    public class MatchBean{

      public String productName ;
      public String brand;
      public String spec;
      public String serialno;
      public String unit ;
      public String num ; 
      public String  isstand ;
      public String ordermethod ; 

      public MatchBean(ConfigurationListDetail__c cg ){
          productName = cg.Configuration__r.ProductName__c == null ? cg.Name : cg.Configuration__r.ProductName__c ;
          brand = cg.Configuration__r.Brand__c;
          spec = cg.Configuration__r.Spec__c;
          serialno = cg.Configuration__r.SerialNo__c;
          unit = cg.Configuration__r.Unit__c;
          num  = String.valueOf(cg.Amount__c);
          isstand = cg.IsStandard__c;
          ordermethod = cg.OrderMethod__c;
      }
    }
    public class QuoteProductBean{
    	public String productId ; 
    	public String relatedId ; 
    	public String name ; 
    	public String brand ; 
    	public String spec ; 
    	public String model ; 
    	public String cate1 ; 
    	public String nccode; 
    	public String serialno ;
    	public String cate2 ;
    	public String cate0;
    	public String coop ; 
    	//public String isPolicy ; 
    	//public String policy ; 
    	public String note; 
    	public Decimal price ; 
    	public Decimal unitprice ; 
    	public Decimal discount ;
    	public Decimal num; 
      public Decimal invoiceDealerPrice; 
      public Decimal hospitalManagerPrice; 

      public String terminalId;
      public String terminal ; 

    	public QuoteProductBean(IntentProduct__c ip,Price__c pr ){
    		productId = ip.Product__c ; 
    		//relatedId = ip.Product__r.MatchingInstrument__c;
    		name = ip.Product__r.ProductName__c;
    		brand = ip.Product__r.Brand__c;
    		spec = ip.Product__r.Spec__c;
    		model = ip.Product__r.Model__c;
    		serialNo = ip.Product__r.SerialNo__c;
    		nccode = ip.Product__r.NCCode__c;
    		cate0 = ip.Product__r.Category0__c;
    		cate1 = ip.Product__r.Category1__c;
    		cate2 = ip.Product__r.Category2__c;
    		coop = '';
    		//isPolicy = '';
    	//	policy = '';
        terminal = ip.TerminalClient__r.Name;
        terminalId = ip.TerminalClient__c;
    		note = '';
    		price = 0;
    		unitprice = 0 ;
    		discount = 0 ; 
    		num = ip.Quantity__c; 
             if(pr != null ){
                invoiceDealerPrice = pr.InvoiceDealerPrice__c;
                hospitalManagerPrice = pr.HospitalManagerPrice__c;
                unitprice = pr.MarketPrice__c;
            }
    	}
    	public QuoteProductBean(QuoteProduct__c p,Price__c pr  ){
        terminal = p.Account__r.Name;
        terminalId = p.Account__c;
    		productId = p.Product__c ; 
    		relatedId = p.RelatedProduct__c ;
    		name = p.Product__r.ProductName__c;
    		brand = p.Product__r.Brand__c;
			  nccode = p.Product__r.NCCode__c;
    		spec = p.Product__r.Spec__c;
    		model = p.Product__r.Model__c;
    		serialNo = p.Product__r.SerialNo__c;
    		cate0 = p.Product__r.Category0__c;
    		cate1 = p.Product__r.Category1__c;
    		cate2 = p.Product__r.Category2__c;
    		//coop = p.CoopType__c;
    		//isPolicy = p.WhetherImplementPolicyPrice__c ; 
    		//policy = p.CompanyPolicyName__c ;
    		note = p.Remarks__c;
    		price = p.SalesPrice__c;
            if(pr != null ){
                invoiceDealerPrice = pr.InvoiceDealerPrice__c;
                hospitalManagerPrice = pr.HospitalManagerPrice__c;
                unitprice = pr.MarketPrice__c;
            }
    		discount = 0; 
    		num = p.Quantity__c; 
    	}
        public QuoteProductBean(ConfigurationListDetail__c p ,Price__c pr,Decimal n,String tId ,String tName  ){
            name = p.Configuration__r.ProductName__c == null ? p.Configuration__r.Name : p.Configuration__r.ProductName__c ;
            brand  = p.Configuration__r.Brand__c;
            spec = p.Configuration__r.Spec__c;
            model = p.Configuration__r.Model__c;
            serialno = p.Configuration__r.SerialNo__c;
            nccode = p.Configuration__r.NCCode__c;
            cate0 = p.Configuration__r.Category0__c;
            cate1 = p.Configuration__r.Category1__c;
            cate2 = p.Configuration__r.Category2__c; 
            productId = p.Configuration__c;
            num = n *p.Amount__c; 
            relatedId = p.InstrumentModel__c;
            terminalId = tId;
            terminal = tName;
            if(pr != null ){
                invoiceDealerPrice = pr.InvoiceDealerPrice__c;
                hospitalManagerPrice = pr.HospitalManagerPrice__c;
                unitprice = pr.MarketPrice__c;
            }
      }
    }


}